<template>
  <div id="app">
    <my-upload
      field="file"
      @crop-success="cropSuccess"
      @crop-upload-success="cropUploadSuccess"
      @crop-upload-fail="cropUploadFail"
      v-model="show"
      :width="250"
      :height="250"
      url="https://upload-z1.qiniup.com"
      :params="params"
      :headers="headers"
      img-format="png"
    ></my-upload>
  </div>
</template>

<script>
import 'babel-polyfill' // es6 shim
import myUpload from 'vue-image-crop-upload'
import * as apiAlbum from '../../../api/album'
import {getNowTime} from '../../../utils/DateUtil'
import {setAlbumCoverUrl} from '../../../api/album'
import {messageError, messageSuccess} from '../../../utils/message'
export default {
  name: 'uploadAlbum',
  data() {
    return {
      show: false,
      params: {
        token: '',
        key: ''
      },
      headers: {},
      imgDataUrl: ''
    }
  },
  components: {
    'my-upload': myUpload
  },
  props: ['albumId'],
  methods: {
    toggleShow() {
      this.getUploadToken()
      this.show = true
    },
    // 剪裁成功后回调
    cropSuccess(imgDataUrl, field) {
      this.params.key = this.$store.getters.name + '/album/' + getNowTime() + '.png'
      this.imgDataUrl = imgDataUrl
    },

    cropUploadSuccess(jsonData, field) {
      let params = {key: this.params.key, id: this.albumId}
      setAlbumCoverUrl(params)
        .then(() => {
          this.$parent.getAlbum()
          messageSuccess('设置封面成功')
          this.show = false
        })
        .catch(() => {
          messageError('设置失败')
        })
    },
    cropUploadFail(status, field) {
      messageError('上传失败')
    },
    getUploadToken() {
      apiAlbum
        .getUploadToken()
        .then(res => {
          this.params.token = res.data
        })
        .catch()
    }
  }
}
</script>

<style scoped></style>
